package com.dpiinc.TechPage

import com.beiji.lib.pen.PenLog
import kotlinx.coroutines.CommonPool
import kotlinx.coroutines.android.UI
import kotlinx.coroutines.launch
import java.io.File

object DataMigrateHelper {

    /**
     *将data/cache目录下的笔记文件迁移到data/file目录,避免因手机的自动清理任务将本地笔记文件删除
     */
    fun migrate(completeCallback: ((result: Boolean) -> Unit)? = null) {

        val srcFolderPath = AIWriteApplication.instance().externalCacheDir!!.absolutePath
        val destFolderPath = AIWriteApplication.instance().getExternalFilesDir(null)!!.absolutePath

        val srcFolder = File(srcFolderPath)
        val destFolder = File(destFolderPath)
        if (!srcFolder.exists()) {
            return
        }
        if (!destFolder.exists()) {
            val result = destFolder.mkdir()
            PenLog.e("mkdir-->" + result.toString())
        }
        launch(CommonPool) {
            srcFolder.listFiles()?.forEach { file ->
                if (file.length() == 0L) {
                    return@forEach
                }
                val destFileName = file.name
                PenLog.e("destFileName -> $destFileName")
                val destFile = File(destFolder, destFileName)
                val result = try {
                    file.copyRecursively(destFile, false)
                } catch (e: Exception) {
                    e.printStackTrace()
                    true
                }
                if (result){
                    file.deleteRecursively()
                }
            }
            launch(UI) {
                completeCallback?.invoke(true)
            }
        }
    }
}